package net.tomblog.app.swingheil.parser;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.tomblog.app.swingheil.model.Article;
import net.tomblog.app.swingheil.oauth.SwingHeilOAuth;
import net.tomblog.app.swingheil.util.L;
import oauth.signpost.basic.DefaultOAuthConsumer;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

/**
 * 다음 까페의 게시판 글 목록을 파싱하는 클래스
 * 
 * @author hyunung.park (parkbear01@gmail.com)
 *
 */
public class DaumArticleParser extends ArticleParser {

	private static final String TAG = "DaumArticleParser";
	
	/* Daum Cafe articles 호출 결과 XML
	<articles totalSize="154" totalNewSize="0">
		<article>
			<boardId>F0jq</boardId>
			<name><![CDATA[<font color="#5D5D5D">소셜댄스 기본 예의</font>]]></name>
			<articleId>168</articleId>
			<userName><![CDATA[알영이]]></userName>
			<commentCount>0</commentCount>
			<regDateTime>1296040371000</regDateTime>
			<viewCount>363</viewCount>
			<hidden>false</hidden>
		</article>
	</articles>
	 */
	private static final String ARTICLES = "articles";
	private static final String ARTICLE = "article";
	private static final String BOARD_ID = "boardId";
	private static final String NAME = "name";
	private static final String ARTICLE_ID = "articleId";
	private static final String USER_NAME = "userName";
	private static final String COMMENT_COUNT = "commentCount";
	private static final String REG_DATE_TIME = "regDateTime";
	private static final String VIEW_COUNT = "viewCount";
	private static final String HIDDEN = "hidden";
	
	private static final String OPEN_API_BASE_URL = "https://apis.daum.net";
	// 즐겨찾는 까페 목록 조회용 URL 
//    private static final String FAVORITE_CAFE_LIST_URL = OPEN_API_BASE_URL + "/cafe/favorite_cafes.xml";
	// 게시판 목록 조회용 URL : Ex)url = CAFE_MENU_LIST_URL + "CrazySwing.xml";
//    private static final String CAFE_MENU_LIST_URL = OPEN_API_BASE_URL + "/cafe/boards/";
	// 글 목록 조회용 URL : Ex)url = CAFE_ARTICLE_LIST_URL + "CrazySwing/F0jq.xml?page=2&listnum=5";
    private static final String CAFE_ARTICLE_LIST_URL = OPEN_API_BASE_URL + "/cafe/articles/";
    /**
     *  글 내용 조회용 URL
     */
	public static final String CAFE_ARTICLE_READ_URL = "http://m.cafe.daum.net";
	
	public DaumArticleParser() {
		mConsumer = new DefaultOAuthConsumer(SwingHeilOAuth.DAUM_CONSUMER_KEY, SwingHeilOAuth.DAUM_CONSUMER_SECRET);
		mConsumer.setTokenWithSecret(SwingHeilOAuth.MY_DAUM_ACCESS_TOKEN, SwingHeilOAuth.MY_DAUM_TOKEN_SECRET);
	}
	
	public List<Article> getArticleList(String cafeId, String boardId, int searchPage, int searchPerPage) throws Exception {
		L.d(TAG, " >>> called getArticleList()");
		
        URL url = null;
        List<Article> articleList = new ArrayList<Article>();;
        
		try {
			url = new URL(CAFE_ARTICLE_LIST_URL 
					+ cafeId + "/" 
					+ boardId + ".xml" 
					+ "?page=" + searchPage 
					+ "&listnum=" + searchPerPage);
			
			mRequest = (HttpURLConnection) url.openConnection();
            mConsumer.sign(mRequest);
            mRequest.connect();
            
			XmlPullParserFactory parserCreator = XmlPullParserFactory.newInstance();
			XmlPullParser parser = parserCreator.newPullParser();
			parser.setInput(mRequest.getInputStream(), null);
			
			int parserEvent = parser.getEventType();
			Article article = null;
			String tag = null;
			
			while (parserEvent != XmlPullParser.END_DOCUMENT) {
				if(mIsCanceled) {
					break;
				}
				switch (parserEvent) {
				case XmlPullParser.START_TAG:
					tag = parser.getName();
//					L.d(TAG, "start tag : " + tag);
					if(tag.equals(ARTICLE)) {
						article = new Article();
						article.setCafeId(cafeId);
					}else if(tag.equals(ARTICLES)) {
					}
					break;
				case XmlPullParser.TEXT:

					String text = parser.getText().trim();
					if(!text.equals("")) {
						L.d(TAG, "text : " + parser.getText() + "[" + text.length() + "]");
						if(tag.equals(BOARD_ID)) {
							article.setBoardId(text);
						}else if(tag.equals(NAME)) {
							article.setArticleTitle(text);
						}else if(tag.equals(ARTICLE_ID)) { 
							article.setArticleId(Integer.parseInt(text));
						}else if(tag.equals(USER_NAME)) {
							article.setNickname(text);
						}else if(tag.equals(COMMENT_COUNT)) {
							article.setCommentCount(Integer.parseInt(text));
						}else if(tag.equals(REG_DATE_TIME)) {
							article.setWriteDate(new Date(Long.parseLong(text)));
						}else if(tag.equals(VIEW_COUNT)) {
							article.setReadCount(Integer.parseInt(text));
						}else if(tag.equals(HIDDEN)) {
							article.setHidden(Boolean.parseBoolean(text));
						}
					}
					break;  
				case XmlPullParser.END_TAG:
					tag = parser.getName();
//					L.d(TAG, "end tag : " + tag);
					if(tag.equals(ARTICLE)) {
						articleList.add(article);
					}
					break;
				}
				parserEvent = parser.next();
			}
		} catch (Exception e) {
			throw e;
		}
		
		return articleList;
	}

	public String getArticleReadURL(Article article) {
		
		String url = CAFE_ARTICLE_READ_URL 
						+ "/" + article.getCafeId() 
						+ "/" + article.getBoardId()
						+ "/" + article.getArticleId();
		return url;
	}
}